package com.newer.textdbnotepad.sdk

import com.google.gson.Gson
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 笔记仓库
 */
@Singleton
class NoteRepository @Inject constructor(private val apiInterface: SecurityApiRepository) {

    /**获取笔记内容*/
    suspend fun getNote(noteKey: String): NoteDetail? {
        val content = apiInterface.getRecord(noteKey)
        return try {
            Gson().fromJson(content, NoteDetail::class.java)
        }catch (e:Exception){
            null
        }

    }

    /**新建笔记*/
    suspend fun createNote(userInfo: UserInfo, noteDetail: NoteDetail): UpdateResponse {
        val newUserInfo = userInfo.copy(notes = userInfo.notes + NoteInfo(noteDetail.noteTitle, noteDetail.noteKey))
        val updateRes = createOrUpdateUser(newUserInfo)
        if (updateRes.isSuccess) {
            return updateNote(noteDetail)
        }
        return updateRes
    }

    /**更新笔记*/
    suspend fun updateNote(noteDetail: NoteDetail): UpdateResponse {
        val content = Gson().toJson(noteDetail)
        return apiInterface.updateRecord(noteDetail.noteKey, content)
    }

    /**获取用户*/
    suspend fun getUser(userKey: String): UserInfo? {
        val content = apiInterface.getRecord(userKey)
        return try {
            Gson().fromJson(content, UserInfo::class.java)
        }catch (e:Exception){
            null
        }

    }

    /**创建或更新用户信息*/
    suspend fun createOrUpdateUser(userInfo: UserInfo): UpdateResponse {
        val content = Gson().toJson(userInfo)
        return apiInterface.updateRecord(userInfo.userKey, content)
    }


}